import utils from '../../../utils/utils'
import { FreeOrderHttp } from '../../../api/freeOrder.js'
import { HomeHttp } from '../../../api/home.js'

const freeOrderModel = new FreeOrderHttp()
const homeModel = new HomeHttp()
const AD_UNIT_ID = 'adunit-b5fbbe96f27d0e64'

Page({
  videoAd:null,
  data: {
    ekey: '',
    freeOrderInfo: {}, // 免单信息
    helpFreeOrderInfo: {}, // 帮助免单信息
    freeOrderDetailsList: [], // 免单详情列表
    sharePosterImg: '', // 分享海报
    shareAppImg: '', // 分享图片
    isHelpFreeOrderInfo: false, // 是否帮助免单
    isShowShare: false, // 是否显示分享
    isShowBannerAd: true, // 是否显示Banner广告
    initUser: true,
    openLogin: false,
    inviteBg: `${utils.pageUrl}mini/images/freeOrder/invite_bg.png`,
  },

  async initPage (options) {
    if (options.orderId) {
      let setDataObj = {}
      setDataObj.orderId = options.orderId
      if (options.ekey) {
        setDataObj.ekey = options.ekey
      }
      this.setData(setDataObj)
      await this.httpGetFreeOrderDetails() // 获取免单详情
      this.httpFreesheetImg().then(() => {
        this.initShare()
      })
    } else {
      utils.msg('订单信息错误！')
    }
  },

  // 初始化分享
  initShare () {
    const { orderId, ekey, freeOrderInfo, shareAppImg } = this.data
    if (ekey) {
      this.shareOption['path'] = `/pages/freeOrder/main/main?orderId=${orderId}$ekey=${ekey}`
    } else {
      this.shareOption['path'] = `/pages/freeOrder/main/main?orderId=${orderId}`
    }
    if (freeOrderInfo.is_user_order) {
      // is_user_order 是否为自己的订单 true：是自己的订单
      this.shareOption['title'] = `我在巷友申请免单，快来帮帮我！`
    } else {
      this.shareOption['title'] = `我在巷友帮好友免单，快来帮帮我！`
    }
    this.shareOption['imageUrl'] = shareAppImg
  },

  // 订单详情
  onOrderDetails () {
    const { orderId } = this.data
    wx.navigateTo({
      url: `/pages/order/ownOrder/ownOrder?id=${orderId}`
    })
  },

  // 邀请免单
  async onInviteFreeOrder () {
    if (!this.data.sharePosterImg) {
      await this.httpCreateShareFreeOrderPoster() // 合成分享海报
    }
    this.setData({
      isShowShare: true
    })
  },

  // 观看广告，帮助免单
  onViewAdHelpFreeOrder () {
    if (!(this.data.userInfo && this.data.userInfo.uid)) {
      this.setData({
        openLogin: true,
        initUser: false
      })
      return
    }
    this.onViewAd()
  },

  // 帮助分享免单
  async onHelpShareFreeOrder () {
    if (!this.data.sharePosterImg) {
      await this.httpCreateShareFreeOrderPoster() // 合成分享海报
    }
    this.setData({
      isShowShare: true
    })
  },

  // 邀请免单详情
  onInvitePeopleDetails () {
    wx.navigateTo({
      url: `/pages/freeOrder/details/details?type=myInvite`
    })
  },

  // 我的余额
  onMyBalance () {
    wx.navigateTo({
      url: `/pages/me/balance/withdrawal/index`
    })
  },

  // 关闭分享海报
  onCloseSharePoster () {
    this.setData({
      isShowShare: false
    })
  },

  // 保存图片发朋友圈
  onSaveImgToPhotosAlbum () {
    const { sharePosterImg} = this.data
    // 获取图片信息
    wx.getImageInfo({
      src: sharePosterImg,
      success(res) {
        // 保存图片到系统相册
        wx.saveImageToPhotosAlbum({
          filePath: res.path,
          success(res) {
            utils.msg('分享图片保存成功！');
          },
          fail(res) {
            utils.msg('分享图片保存失败，请稍候再试！');
          }
        });
      },
      fail(res) {
        utils.msg('分享图片拉取失败，请稍候再试！');
      }
    });
  },

  // 创建视频广告
  createVideoAd() {
    // 在页面onLoad回调事件中创建激励视频广告实例
    if (wx.createRewardedVideoAd && !this.videoAd) {
      this.videoAd = wx.createRewardedVideoAd({
        adUnitId: AD_UNIT_ID
      })
      this.videoAd.onLoad(() => {
        console.log('激励视屏加载成功');
      })
      this.videoAd.onError((err) => {
        console.log(err);
      })
      this.videoAd.onClose((status) => {
        if (status && status.isEnded || status === undefined) {
          this.httpHelpFreeOrder()
        } else {
          utils.msg('请浏览完整个视频！')
        }
      })
    }
  },

  // 看广告
  onViewAd() {
    if (this.videoAd) {
      this.videoAd.load().then(() => {
        this.videoAd.show().catch((err) => {
          console.log('广告显示失败：',err);
        });
      }).catch(err => {
        utils.msg('加载失败，请稍后重试')
      });
    }
  },

  onCloseBannerAd () {
    this.setData({
      isShowBannerAd: false
    })
  },

  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh: async function () {
    await this.httpGetFreeOrderDetails() // 获取免单详情
    wx.stopPullDownRefresh()
  },

   // 用户点击右上角分享
  // onShareAppMessage: function () {},

  // 获取免单相关信息
  httpGetFreeOrderDetails () {
    return freeOrderModel.getFreeOrderDetails({
      order_id: this.data.orderId
    }).then((res) => {
      this.setData({
        freeOrderInfo: res.order_info,
        freeOrderDetailsList: res.free_order_record_list
      })
      if (!res.order_info.is_user_order) {
        this.createVideoAd()
      }
    })
  },

  // 合成分享微信app图片
  httpFreesheetImg() {
    return homeModel.FreesheetImg({
      ordernum: this.data.orderId
    }).then((res) => {
      this.setData({
        shareAppImg: res
      })
    })
  },

  // 合成免单海报
  httpCreateShareFreeOrderPoster() {
    const { ekey, orderId } = this.data
    let requestData = {}
    requestData.order_id = orderId
    if (ekey) {
      requestData.ekey = ekey
    }
    return freeOrderModel.createShareFreeOrderPoster(requestData).then((res) => {
      this.setData({
        sharePosterImg: res.url
      })
      this.shareOption['path'] = `/pages/freeOrder/main/main?orderId=${orderId}&ekey=${res.ekey}`
    })
  },

  // 帮助免单
  httpHelpFreeOrder () {
    const { ekey, orderId } = this.data
    let requestData = {}
    requestData.order_id = orderId
    if (ekey) {
      requestData.ekey = ekey
    }
    return freeOrderModel.helpFreeOrder(requestData).then((res) => {
      this.setData({
        isHelpFreeOrderInfo: true,
        helpFreeOrderInfo: res.order_info,
        freeOrderDetailsList: res.free_order_record_list
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
})
